<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="小区名称" prop="communityName">
        <el-input
          v-model="queryParams.communityName"
          placeholder="请输入小区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属辖区">
            <el-cascader
              :options="treeOptions"
              :props="props"
              collapse-tags
              clearable
              @change="handleChanges"
              ref="cascader"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['community:district:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"

          @click="handleUpdate"
          v-hasPermi="['community:district:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"

          @click="handleDelete"
          v-hasPermi="['community:district:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['community:district:export']"
        >导出</el-button>
      </el-col>
      <template>
        <el-col :span="1.5">
          <label class="el-button el-button--mini el-button--plain" style="cursor: pointer;">
            <input type="file" style="display: none;" @change="handleImport">
            <i class="el-icon-plus"></i> 导入
          </label>
        </el-col>
      </template>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div id="box">
      <ul>
        <li v-for="(v, index) in districtList" :key="index" class="product-item1">
          <div class="product-content3" style="position: relative;">
            <input type="checkbox" v-model="selectedItems" :value="v" class="checkbox-item" @change="handleSelectionChange(v)"
                   style="position: absolute; top: 0; left: 0;"/>
            <img :src="v.image" alt=""/>
            <div class="info" @click="redirectToPopulationPage(v.id)">
              <p>{{ v.communityName }}</p>
              <p>{{ v.centerPoint }}</p> <!-- 显示详细地址 -->
              <p>辖区：{{ v.name }}</p>
              <p>楼栋数量：{{ v.buildingCount }}</p>
              <p>住户数：{{ v.populationNum }}</p>
            </div>
          </div>
          <div class="additional-info">
            <p @click="handlePopulationClick(v.id)">实有人口：{{ v.populationNum }}</p>
            <p @click="handleEstateClick(v.id)">实有房屋：{{ v.realEstateNum }}</p>
            <p @click="handleUnitClick(v.id)">实有单位：{{ v.unitNum }}</p>
            <p @click="handleVehiclesClick(v.id)">实有车辆：{{ v.vehicleNum }}</p>
            <p @click="handleCacheClick(v.id)">实有力量：{{ v.buildingCount }}</p>
            <p @click="handleFacilitiesClick(v.id)">实有设备：{{ v.securityFacilitiesNum }}</p>
          </div>
        </li>
      </ul>
    </div>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-row>
        <el-col :span="9">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="小区名称" prop="communityName">
              <el-input v-model="form.communityName" placeholder="请输入小区名称" />
            </el-form-item>
            <el-form-item label="经纬度区域" prop="areaPoint">
              <el-input v-model="form.areaPoint" placeholder="请输入经纬度区域" />
            </el-form-item>
<!--            <el-form-item label="出入口经纬度" prop="passagewayPoint">-->
<!--              <el-input v-model="form.passagewayPoint" placeholder="请输入出入口经纬度" />-->
<!--            </el-form-item>-->
            <el-form-item label="小区图片" prop="image">
              <image-upload v-model="form.image"/>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item label="所属辖区">
                  <el-cascader
                    v-model="form.areaIds"
                    :options="treeOptions"
                    :props="props"
                    collapse-tags
                    clearable
                    @change="handleChange"
                    ref="cascader"
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="15">
          <Map ref="Map" v-model="form.areaPoint" />
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDistrict, getDistrict, delDistrict, addDistrict, updateDistrict ,handleImportDistrict} from "@/api/community/district";
import Map from '@/components/Map/maptwo.vue'
import { treeOptions } from '@/api/community/area'
import { getVehicles } from '@/api/community/vehicles'

export default {
  name: "District",
  components: { Map },
  data() {
    return {
      treeOptions: [],
      props: { expandTrigger: 'hover', value: 'id' },
      isAsd:0,
      address: '',
      selectedItems:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      name: [],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      //multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小区表格数据
      districtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        communityName: null,
        centerPoint: null,
        areaPoint: null,
        passagewayPoint: null,
        image: null,
        name: null,
        areaId: null,
      },
      long:null,
      lat:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        communityName: [
          { required: true, message: "小区名称不能为空", trigger: "blur" }
        ],
        areaPoint: [
          { required: true, message: "经纬度区域不能为空", trigger: "blur" }
        ],
        passagewayPoint: [
          { required: true, message: "出入口经纬度不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTreeOptions();
  },

  methods: {
    handleChange(value){
      console.log(value)
      this.form.areaIds = value;
      this.form.areaId = value[value.length-1];
    },
    handleChanges(value){
      this.queryParams.areaId = value[value.length-1];
    },
    getTreeOptions() {
      treeOptions(1).then(response => {
        this.treeOptions = response.data;
      });
    },
    redirectToPopulationPage(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    getAddressByLocation(location) {
      return new Promise((resolve, reject) => {
        const geocoder = new AMap.Geocoder({
          radius: 1000, // 返回结果周边的范围，单位：米
          extensions: 'all', // 是否返回扩展信息
        });

        geocoder.getAddress(location, (status, result) => {
          let formatted = '解析失败';
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              formatted = result.regeocode.formattedAddress;
            } else {
              formatted = '未找到地址信息';
            }
          } else {
            formatted = "地址解析失败";
          }
          resolve(formatted);
        });
      });
    },
    getList() {
      this.loading = true;
      this.districtList = []; // 清空列表

      listDistrict(this.queryParams).then(response => {
        this.districtList = response.rows;
        this.total = response.total;

        const promises = this.districtList.map(district => {
          const strings = district.centerPoint.split(",");
          const location = [strings[0], strings[1]];

          return this.getAddressByLocation(location);
        });

        Promise.all(promises).then(addresses => {
          this.districtList.forEach((district, index) => {
            district.centerPoint = addresses[index];
          });
          this.loading = false;
        }).catch(error => {
          console.error('加载或解析地址失败', error);
          this.loading = false;
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        communityName: null,
        centerPoint: null,
        areaPoint: null,
        passagewayPoint: null,
        image: null,
        name: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(item) {
      const id = item.id;
      const name = item.communityName;
      if (this.selectedItems.includes(item)) {
        if (!this.ids.includes(item)) {
          this.ids.push(id);
          this.name.push(name);
        }
      } else {
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
        const index1 = this.name.indexOf(name);
        if (index1 !== -1) {
          this.name.splice(index1, 1);
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.$refs.Map.handleClearDraw();
      this.title = "添加小区";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      if (this.ids.length === 1) {
        const id = this.ids[0];
        const name = this.name[0];
        this.$message.info("开始修改操作，：" + name);
        getDistrict(id).then(response => {
          this.form = response.data;
          this.form.areaIds = this.form.areaIds.split(',').map(Number);
          console.log(this.form.areaIds);
          this.open = true;
          this.title = "修改小区";
        });
      } else if (this.ids.length > 1) {
        this.$message.warning("每次只能修改一个小区信息统计，请选择单个项目进行修改。");
      } else {
        this.$message.warning("请选择一个小区信息统计项目进行修改。");
      }
    },
    /** 提交按钮 */
    submitForm() {
      // if (this.form.areaPoint.length === 0){
      //   this.$modal.msgError("请选择区域");
      // }
      this.$refs["form"].validate(valid => {

        if (valid) {
          if (this.form.id != null) {
            this.calculateCenterPoint()
            this.form.areaPoint=JSON.stringify(this.form.areaPoint);
            updateDistrict(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.ids=[]
              this.name=[]
              this.selectedItems=[]
              this.getList();
            });
          } else {
            this.form.areaIds = this.form.areaIds.join(',')
            this.calculateCenterPoint()
            this.form.areaPoint=JSON.stringify(this.form.areaPoint);
            addDistrict(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    calculateCenterPoint() {
      let totalLat = 0;
      let totalLng = 0;
      this.form.areaPoint.forEach(coord => {
        totalLat += coord.lat;
        totalLng += coord.lng;
      });

      const avgLat = totalLat / this.form.areaPoint.length;
      const avgLng = totalLng / this.form.areaPoint.length;

      this.form.centerPoint = [avgLng.toFixed(6),avgLat.toFixed(6)].join(',')

      console.log(this.form)
    },
    /** 删除按钮操作 */
    handleDelete() {
      const ids = this.ids;
      const name = this.name;
      this.$modal.confirm('是否确认删除小区名称为"' + name + '"的数据项？').then(function() {
        return delDistrict(ids);
      }).then(() => {
        this.ids=[]
        this.name=[]
        this.selectedItems=[]
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.districtIds = this.ids;
      console.log(this.queryParams.districtIds);
      this.download('community/district/export', {
        ...this.queryParams
      }, `district_${new Date().getTime()}.xlsx`)
      this.ids=[]
      this.name=[]
      this.selectedItems=[]
    },

    /** 导入按钮操作 */
    handleImport(event) {
      const file = event.target.files[0]; // 获取上传的文件
        handleImportDistrict(file).then(res=>{
          if(200===res.code){
            window.location.reload();
            this.$modal.msgSuccess("导入成功");
          }else {
            this.$modal.msgSuccess("导入失败，请重新导入");
          }
        });
    },
    // 查询小区 实有人口
    handlePopulationClick(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有房屋
    handleEstateClick(id) {
      this.$router.push({
        path: '/community/estate/' + id,
        name: 'Estate',
        params: {
          id: id
        }
      })
    },

    // 查询小区 实有单位
    handleUnitClick(id) {
      this.$router.push({
        path: '/community/unit/' + id,
        name: 'Unit',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有车辆
    handleVehiclesClick(id) {
      this.$router.push({
        path: '/community/vehicles/' + id,
        name: 'Vehicles',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有设备
    handleFacilitiesClick(id) {
      this.$router.push({
        path: '/community/facilities/' + id,
        name: 'Facilities',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有力量
    handleCacheClick() {
      alert('待开发');
    },
    handleOpen(){
      this.dialogVisible=true;
    },
  }
};
</script>
<style scoped>
#box ul {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 0;
}
#box {
  height: 500px;
  overflow-y: auto;
}

.product-item1 {
  flex: 0 0 calc(33.33% - 20px); /* 每行显示三个商品，每个商品占据33.33%的宽度，减去20px的外边距 */
  list-style: none;
  border: 1px solid #eee;
  margin-bottom: 20px; /* 调整每个商品之间的底部间距 */
  margin-right: 20px; /* 调整商品之间的右侧间距 */
}

.product-content3 {
  display: flex;
  align-items: center; /* 垂直居中图片和信息 */
  padding: 10px;
}

.product-content3 img {
  width: 100px; /* 调整图片宽度 */
  height: 100px;
  margin-right: 10px; /* 图片与信息之间的间距 */
}

.info {
  flex: 1; /* 让信息部分占据剩余空间 */
}

.info h4,
.info p {
  margin: 0;
}

.additional-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列布局 */
  grid-gap: 10px; /* 设置网格之间的间距 */
}

.additional-info p {
  margin: 0;
}
</style>
